package com.qing.study.controller;

import com.qing.study.comm.Result;
import com.qing.study.util.RandomNumUtil;
import com.qing.study.util.RedisUtil;
import io.swagger.annotations.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "向Redis中存取数据")
//排序
@ApiSort(value = 1)
@RequestMapping("redis")
public class RedisController {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RedisUtil redisUtil;

    @ApiOperation("存储数据")
    @GetMapping("setRedisData")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "phoneNum", value = "手机号", dataType = "String", required = true)})
    public Result setRedisData(String phoneNum) {
        if (redisTemplate.opsForValue().get(phoneNum) != null) {
            return Result.ok("手机号：" + phoneNum + "在redis中对应的验证码为：" + redisTemplate.opsForValue().get(phoneNum));
        } else {
            String num = RandomNumUtil.generateRandomNumber(4);
            redisTemplate.opsForValue().set(phoneNum, num, 10, TimeUnit.MINUTES);
            return Result.ok();
        }
    }


    @ApiOperation("取出数据")
    @GetMapping("getRedisData")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "phoneNum", value = "手机号", dataType = "String", required = true)})
    public Result getRedisData(String phoneNum) {
        return Result.ok(redisTemplate.opsForValue().get(phoneNum));
    }

    @ApiOperation("使用RedisUtil向Redis中存储数据")
    @GetMapping("setKvByRU")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "key",value = "key值"),
            @ApiImplicitParam(name = "value",value = "value值")
    })
    public Result setKvByRU(String key,String value) {
        redisUtil.set(key,value);
        return Result.ok();
    }
    @ApiOperation("使用RedisUtil从Redis中获取数据")
    @GetMapping("getVByRU")
    @ApiImplicitParam(name = "key",value = "key值")
    public Result getVByRU(String key) {
        return Result.ok(redisUtil.get(key));
    }
}
